﻿CREATE PROCEDURE [ServiceEngine].[SubscribeToEvent] 
	@EventName varchar(100),
	@CallbackURI varchar(200),
	@Expires datetime OUTPUT 
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	Declare @EventID as uniqueidentifier
	
	BEGIN TRY
		BEGIN TRANSACTION

	Select  @EventID = EventID
	From	[ServiceEngine].[Events] e
	Where	e.[Name] = @EventName
	
	if (@EventID is not null) BEGIN
	
		set		@Expires = dateadd(hour,8,getdate())
		
		update [ServiceEngine].[EventRegistrations]
		set		Expires = @Expires
		where	EventID = @EventID
		and		CallbackURI = @CallbackURI
		
		if (@@ROWCOUNT = 0) BEGIN
		
			Insert Into [ServiceEngine].[EventRegistrations] (EventID, CallbackURI, Expires)
			Values (@EventID, @CallbackURI, @Expires)
		
		END

		COMMIT TRANSACTION	
	END 

	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
	
	RETURN
END


